<template>
  <basic-modal
    v-bind="$attrs"
    show-confirm
    @confirm="handleSubmit"
    @close="handleClose"
    @cancel="handleCancel"
  >
    <n-space vertical>
      <n-card :title="item.label" v-for="item in allConditions">
        <n-checkbox-group v-model:value="ownSelectedConditions[item.value]">
          <n-space>
            <n-checkbox
              v-for="attribteValue in item.data"
              :key="attribteValue.value"
              :value="attribteValue.value"
              :label="attribteValue.label"
            />
          </n-space>
        </n-checkbox-group>
      </n-card>
    </n-space>
  </basic-modal>
</template>
<script setup lang="ts">
import { watch, ref } from "vue";
import { isEmpty, cloneDeep } from "lodash-es";
import { IFilterModalProps, SelectedCondition } from "./props";

const props = withDefaults(defineProps<IFilterModalProps>(), {});

const ownSelectedConditions = ref<SelectedCondition>({});

const emits = defineEmits(["confirm", "close", "cancel", "update:show"]);

watch(
  () => props.selectedConditions,
  (newVal) => {
    if (!isEmpty(newVal)) {
      ownSelectedConditions.value = cloneDeep(newVal);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const handleClose = () => {
  emits("update:show", false);
  emits("close");
  ownSelectedConditions.value = cloneDeep(props.selectedConditions);
};

const handleCancel = () => {
  emits("update:show", false);
  emits("cancel");
  ownSelectedConditions.value = cloneDeep(props.selectedConditions);
};

const handleSubmit = () => {
  emits("update:show", false);
  emits("confirm", ownSelectedConditions.value);
};
</script>
